import {
  listAllInvokeInterfaceInfoUsingGET,
  listTopInvokeInterfaceInfoUsingGET,
} from '@/services/yuapi-backend/analysisController';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { TableDropdown } from '@ant-design/pro-table/lib';
import { Button, Dropdown } from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useRef, useState } from 'react';

const columns: ProColumns<API.UserInterfaceInfo>[] = [
  {
    title: '接口',
    dataIndex: 'name',
    copyable: true,
    ellipsis: true,
    tip: '标题过长会自动收缩',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
  {
    disable: true,
    title: '状态',
    dataIndex: 'status',
    filters: true,
    onFilter: true,

    ellipsis: true,
    valueEnum: {
      0: {
        text: '关闭',
        status: 'Error',
        disabled: true,
      },
      1: {
        text: '开启',
        status: 'Processing',
      },
    },
  },
  {
    title: '总调用次数',
    key: 'totalNum',
    dataIndex: 'totalNum',
    sorter: true,
    hideInSearch: true,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <a key="editable" onClick={() => {

      }}>
        接口限流
      </a>,
      <TableDropdown
        key="actionGroup"
        onSelect={() => action?.reload()}
        menus={[
          { key: 'copy', name: '复制' },
          { key: 'delete', name: '删除' },
        ]}
      />,
    ],
  },
];

const InterfaceAnalysis: React.FC = () => {
  const [data, setData] = useState<API.InterfaceInfoVO[]>([]);

  useEffect(() => {
    try {
      listAllInvokeInterfaceInfoUsingGET().then((res) => {
        if (res.data) {
          setData(res.data);
        }
      });
    } catch (e: any) {}
    // todo 从远程获取数据
  }, []);
  //映射
  const numberData = data.map((item) => {
    return {
      value: item.totalNum,
    };
  });
  //映射
  const nameData = data.map((item) => {
    return {
      value: item.name,
    };
  });
  // 映射：{ value: 1048, name: 'Search Engine' },
  const chartData = data.map((item) => {
    return {
      value: item.totalNum,
      name: item.name,
    };
  });
  const list = {
    xAxis: {
      type: 'category',
      data: nameData,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: numberData,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)',
        },
      },
    ],
  };

  const option = {
    title: {
      text: '调用次数最多的接口TOP',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  const actionRef = useRef<ActionType>();

  return (
    <PageContainer>
      <ReactECharts option={option}></ReactECharts>
      <ReactECharts option={list}></ReactECharts>
      <ProTable<API.UserInterfaceInfo>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          const interfaceInfoVoList = await listAllInvokeInterfaceInfoUsingGET();
          return {
            data: interfaceInfoVoList.data,
          };
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="调用分析"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary">

          </Button>,
        ]}
      />
    </PageContainer>
  );
};
export default InterfaceAnalysis;
